package fr.epita.mti
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.net.URLRequest;
	import flash.system.System;
	import flash.utils.setTimeout;
	
	import mx.charts.CategoryAxis;
	import mx.collections.ArrayCollection;
	import mx.controls.ProgressBar;
	import mx.events.CubeEvent;

	/**
	 * Le moteur de son qui permet de manipuler la chanson chargée
	 * @author laurent
	 */ 
	public class SongEngine
	{
		/**
		 * Contient la chanson actuelle
		 */
		public var currentSong:Sound = null;
		public var songScanner:Scan = new Scan();

		public var sndChannel:SoundChannel = new SoundChannel();
		public var progressBar:ProgressBar = new ProgressBar();

		/**
		 * Constructeur du moteur de son
		 */
		public function SongEngine()
		{
			currentSong = null;
		}
		
		public function songInProgress():String
		{
			if (currentSong != null)
			{
				trace ("SOng:" +this.currentSong.id3.songName);
				return this.currentSong.id3.songName;
			}
				
			return "";
		}
		
		/**
		 * Cette methode charge une chanson a partir du path
		 * @param Le chemin absolu de la chanson
		 */
		public function loadSong(path:String):void
		{
			progressBar.mode = "manual";
			progressBar.visible = true;
			try
			{
				var str:URLRequest = new URLRequest(path);
				currentSong = new Sound(str);
				playSong();
			}
			catch (evt:IOErrorEvent)
			{
				trace(evt);
			}
			catch (error:Error)
			{
				trace("ERROR -> " + error.message);
			}
		}
		
		/**
		 * Lance la lecture de la chanson dans currentSong
		 */
		public function playSong():void
		{
			if (currentSong != null)
			{				
				sndChannel = currentSong.play();
			}
		}
		
		/**
		 * Stoppe la lecture de la chanson (bouton non implementé)
		 */
		public function stopSong():void
		{
			if (sndChannel != null)
			{
				sndChannel.stop();
//				currentSong.close();
			}
		}
		public function get bytesLoaded():Number {
			if(sndChannel == null)
				return 0;
			/*var position:Number = sndChannel.position / 1000; 
			if (position >= 60)
				position /= 60 * 100;
			*/
			return sndChannel.position;
		}
		
		public function get bytesTotal():Number {
			if (currentSong != null)
				return currentSong.length;
			return 0;
		}
		
		public function clearProgress():void {
			sndChannel = null;
		}
	}
}